<script setup lang="ts">
import { useRouter } from 'vue-router';
import type { RouterType, TransitionRouterViewProps } from './types';
import { ref } from 'vue';

const router = useRouter();
const props = withDefaults(defineProps<TransitionRouterViewProps>(), {
  routerType: 'none'
});

const transitionName = ref<RouterType>('none');

router.beforeEach(to => {
  transitionName.value = props.routerType;

  if (props.routerType === 'push') {
    virtualTaskStack.value.push(to.name as string);
  } else if (props.routerType === 'back') {
    virtualTaskStack.value.pop();
  }

  if (to.name === props.mainComponentName) {
    clearVirtualTaskStack();
  }
});

const isAnimation = ref<boolean>(false);
const onBeforeEnter = () => {
  isAnimation.value = true;
};
const onAfterEnter = () => {
  // isAnimation.value = false;
};

const virtualTaskStack = ref<string[]>([props.mainComponentName]);
function clearVirtualTaskStack() {
  virtualTaskStack.value = [props.mainComponentName];
}

defineOptions({ name: 'MTransitionRouterView' });
</script>

<template>
  <RouterView v-slot="{ Component, route }">
    <Transition
      :name="transitionName"
      @before-enter="onBeforeEnter"
      @after-enter="onAfterEnter"
    >
      <KeepAlive :include="virtualTaskStack">
        <component
          :class="{ 'fixed top-0 left-0 z-50 w-screen': isAnimation }"
          :is="Component"
          :key="route.fullPath"
        />
      </KeepAlive>
    </Transition>
  </RouterView>
</template>

<style lang="css" scoped>
.push-enter-active {
  animation-name: push-in;
  animation-duration: 0.5s;
}

.push-leave-active {
  animation-name: push-out;
  animation-duration: 0.5s;
}

@keyframes push-in {
  0% {
    transform: translate(100%, 0);
  }
  100% {
    transform: translate(0, 0);
  }
}

@keyframes push-out {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-50%, 0);
  }
}

.back-enter-active {
  animation-name: back-in;
  animation-duration: 0.5s;
}

.back-leave-active {
  animation-name: back-out;
  animation-duration: 0.5s;
}

@keyframes back-in {
  0% {
    width: 100%;
    transform: translate(-100%, 0);
  }
  100% {
    width: 100%;
    transform: translate(0, 0);
  }
}

@keyframes back-out {
  0% {
    width: 100%;
    transform: translate(0, 0);
  }
  100% {
    width: 100%;
    transform: translate(50%, 0);
  }
}
</style>
